// pages/userInfo/index.js
import {
  API,
  getUrl
} from '../../utils/api'
import {
  checkPhone
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userPhone: '',
    phoneNumber: '',
    address: '', // 详细地址
    addressCode: [], // 省市区code
    addressName: [], // 省市区code
    addressSumName: '',
    classes: '', // 班级
    familyName: '', // 家长姓名
    grade: '', // 年级
    nickName: '', // 昵称
    register: false, // 完善个人信息,
    schoolId: '', // 学校ID
    schoolName: '', // 学校名称
    studentName: '', // 学生姓名
    clasaList: [],
    gradeAndClassIndex: [],
    schoolList: [], // 全部学校列表
    schoolIndex: -1,
    errorMsg: '',
    beforeData: {}
  },
  bindAddressPickerChange(e) {
    this.setData({
      addressCode: e.detail.code,
      addressName: e.detail.value
    })
    this.setData({
      addressSumName: this.getAddressSumName()
    });
  },
  bindSchoolPickerChange(e) {
    this.setData({
      schoolIndex: e.detail.value,
      gradeAndClassIndex: []
    })
  },
  bindGradeAndClassPickerChange(e) {
    this.setData({
      gradeAndClassIndex: e.detail.value
    })
  },
  getAddressSumName() {
    if (this.data.addressName.length == 0) {
      return '';
    }
    let address = '';
    for (let index = 0; index < this.data.addressName.length; index++) {
      address += this.data.addressName[index];
    }
    return address;
  },
  bindInput(e) {
    let data = {};
    data[e.target.dataset.key] = e.detail.value;
    this.setData(data)
  },
  bindSumbitBtnClick(e) {
    if (e.detail.encryptedData && this.data.userPhone.length == 0) {
      wx.request({
        url: getUrl(API.PHONE_NUMBER),
        method: "POST",
        data: {
          openid: this.data.beforeData.openid,
          session_key: this.data.beforeData.sessionKey,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        },
        success: (res) => {
          if (res.data.data.phoneNumber) {
            this.setData({
              userPhone: res.data.data.phoneNumber
            })
          }
          this.onSubmit();
        }
      });
    } else {
      this.onSubmit();
    }
  },
  onSubmit() {
    let params = {};
    let msg = '';
    if (this.data.addressCode.length != 3) {
      msg = "请选择所在地区"
    } else {
      params.provinceCode = this.data.addressCode[0];
      params.province = this.data.addressName[0];
      params.cityCode = this.data.addressCode[1];
      params.city = this.data.addressName[1];
      params.countyCode = this.data.addressCode[2];
      params.county = this.data.addressName[2];
    }

    if (this.data.schoolIndex == -1) {
      msg = "请选择所在学校"
    } else {
      params.schoolId = this.data.schoolList[this.data.schoolIndex].schoolId;
      params.schoolName = this.data.schoolList[this.data.schoolIndex].schoolName;
    }

    if (this.data.gradeAndClassIndex.length != 2) {
      msg = "请选择所在班级"
    } else {
      let gradeList = this.data.schoolList[this.data.schoolIndex].gradeList;
      params.grade = gradeList[this.data.gradeAndClassIndex[0]];
      params.classes = this.data.clasaList[this.data.gradeAndClassIndex[1]];
    }

    if (this.data.studentName) {
      params.studentName = this.data.studentName;
    } else {
      msg = "请输入学生姓名";
    }

    if (this.data.familyName) {
      params.familyName = this.data.familyName;
    } else {
      msg = "请输入家长姓名";
    }

    if (this.data.phoneNumber) {
      if (!checkPhone(this.data.phoneNumber)) {
        msg = "手机号格式不正确";
      } else {
        params.phoneNumber = this.data.phoneNumber;
      }
    } else {
      msg = "请输入家长手机号";
    }

    if (this.data.address) {
      params.address = this.data.address;
    } else {
      msg = "请输入家庭地址";
    }

    if (msg) {
      this.setData({
        errorMsg: msg
      })
      return;
    }
    params.openid = this.data.beforeData.openid;
    wx.request({
      url: getUrl(API.USER_SAVE),
      method: "POST",
      data: params,
      success: (res) => {
        if (res.data.data) {
          this.setData({
            errorMsg:res.data.msg
          })
          const eventChannel = this.getOpenerEventChannel()
          res.data.data.register=false;
          eventChannel.emit('saveData', {data:res.data.data});
          wx.navigateBack();
        } else {
          this.setData({
            errorMsg: res.data.msg||'保存失败'
          })
        }      
      }
    });
  },
  backToHome() {
    wx.navigateBack();
  },
  closeMsgDialog() {
    this.setData({
      errorMsg: ''
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const eventChannel = this.getOpenerEventChannel();
    if (Object.keys(eventChannel).length > 0)
      eventChannel.on('sendData', (data) => {
        this.setData({
          clasaList: data.clasaList,
          schoolList: data.schoolList,
          beforeData: data
        })
      })
    wx.getLocation({
      success: res => {
        wx.request({
          url: getUrl(API.USER_GEO_CODE),
          data: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res) => {
            let addressInfo = res.data.data;
            if (addressInfo) {
              this.setData({
                addressCode: [addressInfo.provinceCode, addressInfo.cityCode, addressInfo.countyCode],
                addressName: [addressInfo.province, addressInfo.city, addressInfo.county]
              });
              this.setData({
                addressSumName:this.getAddressSumName()
              })
            }
          }
        });
      },
    })
  }
})